import xml2js from 'xml2js'
import template from './tpl'
import sha1 from 'sha1'
function parseXML (xml) {
  return new Promise((resolve, reject) => {
    xml2js.parseString(xml, {trim: true}, (err, content) => {
      if (err) reject(err)
      else resolve(content)
    })
  })
}

function formatMessage (result) {
  let message = {}

  if (typeof result === 'object') {
    // Object.keys() 返回该对象用下标表示的数组
    const keys = Object.keys(result)

    for (let i = 0; i < keys.length; i++) {
      let item = result[keys[i]]
      let key = keys[i]

      if(!(item instanceof Array) || item.length === 0) {
        continue
      }
      if (item.length === 1) {
        let val = item[0]

        if (typeof val === 'object') {
          message[key] = formatMessage(val)
        } else {
          // 去掉前后的空格 string.trim()
          message[key] = (val || '').trim()
        }
      } else {
        message[key] = []
        for (let j=0; j < item.length; j++){
          message[key].push(formatMessage(item[j]))
        }
      }
    }
  }
  return message
}

function tpl (content, message){
  let type = 'text'
  if(Array.isArray(content)) {
    type = 'news'
  }
  if (!content) {
    content = 'Empty News'
  }
  if (content && content.type) {
    type = content.type
  }

  let info = Object.assign({}, {
    content: content,
    createTime: new Date().getTime(),
    msgType:  type,
    toUserName: message.FromUserName,
    fromUserName: message.ToUserName
  })
  return template(info)
}
function signIt (nonce, ticket, timestamp, url) {
  const ret = {
    jsapi_ticket: ticket,
    nonceStr: nonce,
    timestamp: timestamp,
    url: url
  }

  const string = raw(ret)
  // 将字符串进行哈希
  const sha = sha1(string)

  return sha
}
// 随机字符串 36位，截取2~15
function createNonce () {
  return Math.random().toString(36).substr(2, 15)
}
// 生成时间撮 向下取整 +号是为了隐形转换
function createTimestamp () {
  return parseInt(new Date().getTime() / 1000, 0) + ''
}
// 拼接成字符串string
function raw (args) {
  // object.key() 遍历key，返回所以key的一个数组
  let keys = Object.keys(args)
  // sort排序 （字母）num要加函数
  keys = keys.sort()
  let newArgs = {}
  keys.forEach((key) => {
    
    // toLowerCase() 转换小写
    newArgs[key.toLowerCase()] = args[key]
  })
  let str = ''

  for (let k in newArgs) {
    str += '&' + k + '=' + newArgs[k]
  }
  return str.substr(1)
}
// 返回需要的参数
function sign (ticket, url) {
  const nonce = createNonce()
  const timestamp = createTimestamp()
  const signature = signIt(nonce, ticket, timestamp)

  return {noncestr: nonce, timestamp: timestamp, signature: signature}
}

export {
  formatMessage, 
  parseXML,
  tpl,
  sign
}